<script setup lang="ts">
import { reactive, ref, Ref } from "vue";
import { ElMessage } from "element-plus";
import type { UploadFile, UploadFiles, UploadProps, UploadRawFile } from "element-plus/es/components/upload";
import type { FormRules, FormInstance } from "element-plus/es/components/form";
import { Awaitable } from "element-plus/lib/utils";
import { trademark } from "@/api/product/trademarkApi/interface.ts";
import useTrademarkStore from "@/pinia/modules/product/trademarkStore/trademarkStore.ts";

const trademarkStore = useTrademarkStore();

const emits = defineEmits(["success"]);

/* el-for表单组件实例 */
const formRef: Ref<FormInstance | undefined> = ref<FormInstance>();
/* 表单数据对象 */
const formData: trademark = reactive<trademark>({ logoUrl: "", tmName: "" });
/* 表单规则对象 */
const formRules = reactive<FormRules<trademark>>({
  logoUrl: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
  tmName: [{ required: true, message: "请上传品牌图片" }],
});
/* 文件上传成功的回调函数 */
const updateSuccess: UploadProps["onSuccess"] = (response: any, uploadFile: UploadFile, uploadFiles: UploadFiles): void => {
  if (response.code === 200) {
    formData.logoUrl = response.data;
    ElMessage.success("上传成功");
    // 当图片上传成功的时候清理logoUrl字段的表单验证信息。
    formRef.value?.clearValidate("logoUrl");
  } else {
    ElMessage.error("上传失败");
    console.log(response, uploadFile, uploadFiles);
  }
};
/* 文件上传之前的回调函数 */
const beforeUpload: UploadProps["beforeUpload"] = (rawFile: UploadRawFile): Awaitable<boolean> => {
  const isImage: boolean = rawFile.type.startsWith("image");
  const size: boolean = rawFile.size / 1024 / 1024 > 2;
  if (!isImage) {
    ElMessage.error("只能上传图片");
    return false;
  } else if (size) {
    ElMessage.error("上传的图片不能超过2MB!");
    return false;
  }
  return true;
};
/* 用于做添加一个品牌的回调函数 */
const doAdd = async () => {
  try {
    const addResult: string = await trademarkStore.addTradeMark(formData);
    ElMessage.success(addResult);
    emits("success");
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};
/* 用于做编辑一个品牌的回调函数 */
const doEdit = async () => {
  try {
    const editResult: string = await trademarkStore.updateTradeMark(formData);
    ElMessage.success(editResult);
    emits("success");
  } catch (error:any) {
    ElMessage.error(error.message);
  }
};
/* 数据回显*/
const findTrademark = (trade: trademark) => {
  formData.id = trade.id;
  formData.logoUrl = trade.logoUrl;
  formData.tmName = trade.tmName;
};
const doValidate: () => Promise<boolean | undefined> = async (): Promise<boolean | undefined> => {
  return formRef.value?.validate(() => {
  }).catch(error => error);
};
/* 点击确定按钮的回调函数(添加或者编辑一个品牌) */
const handleSubmit = async () => {
  if (!await doValidate()) return;
  if (formData.id) {
    doEdit();
  } else {
    doAdd();
  }
};
/* 重置该表单项将其值重置为初始值并移除校验结果的回调函数 */
const resetFields: () => void = (): void => {
  formRef.value?.resetFields();
};
defineExpose({
  resetFields,
  findTrademark,
});
</script>
<template>
  <el-form label-width="100px" :model="formData" :rules="formRules" ref="formRef">
    <el-form-item label="品牌名称" prop="tmName">
      <el-input placeholder="请输入品牌名称" v-model="formData.tmName"></el-input>
    </el-form-item>
    <el-form-item label="品牌LOGO" prop="logoUrl">
      <el-upload class="avatar-uploader" action="/api//admin/product/fileUpload" :show-file-list="false" :on-success="updateSuccess" :before-upload="beforeUpload">
        <img v-if="formData.logoUrl" :src="formData.logoUrl" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon">
          <Plus />
        </el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button type="danger">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.el-form {
  width: 65%;

  .avatar-uploader {
    height: 178px;

    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }

  .avatar-uploader:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
}
</style>
